/*
 * @Author: LVGRAPE
 * @LastEditors: LVGRAPE
 */
#include "rgb.h"
#include "pwr.h"
#include <rtthread.h>
#define DBG_TAG "fc_error"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

uint32_t rgb_state = 0;
uint16_t rgb_state_show = 0;
uint32_t fc_error_flag;

const uint8_t blue_color[3] = {0, 0, 255};
const uint8_t greenColor[3] = {0, 255, 0};
const uint8_t yellow_color[3] = {255, 255, 0};
const uint8_t red_color[3] = {255, 0, 0};
const uint8_t purple_color[3] = {102, 0, 204};

const uint8_t white_color[3] = {255, 255, 255};
void rgb_state_set(rgb_state_t s)
{
    rgb_state |= (1 << s);
}
void rgb_state_clr(rgb_state_t s)
{
    rgb_state &= ~(1 << s);
}
uint32_t get_rgb_state(void)
{
    return rgb_state;
}
struct rgbColorState
{
    const uint8_t *color;
    uint8_t mode;
};
enum
{
    RGB_STATE_MODE_FAST = 0,
    RGB_STATE_MODE_SLOW,
    RGB_STATE_MODE_BREATH,
};

struct rgbColorState rgbColorState[RGB_STATE_COUNT] =
    {

        {greenColor, RGB_STATE_MODE_SLOW},

};

void rgb_state_handle()
{
    if (hardware_is_pwrkey_trig())
        return;
#define SHOW_TIME 250
    static uint8_t stateCnt;
    static uint8_t rgb_scnt = 0;

    if (rgb_scnt++ >= SHOW_TIME)
    {
        rgb_scnt = 0;
        stateCnt++;
    }
    if ((1 << stateCnt) & rgb_state)
    {
        uint8_t r = 0, g = 0, b = 0;
        switch (rgbColorState[stateCnt].mode)
        {
        case RGB_STATE_MODE_FAST:
            if ((rgb_scnt % (SHOW_TIME / 4)) < (SHOW_TIME / 8))
            {
                r = rgbColorState[stateCnt].color[0];
                g = rgbColorState[stateCnt].color[1];
                b = rgbColorState[stateCnt].color[2];
            }
            break;
        case RGB_STATE_MODE_SLOW:
            if (rgb_scnt < (SHOW_TIME / 2))
            {
                r = rgbColorState[stateCnt].color[0];
                g = rgbColorState[stateCnt].color[1];
                b = rgbColorState[stateCnt].color[2];
            }
            break;
        case RGB_STATE_MODE_BREATH:
            if (rgb_scnt < (SHOW_TIME / 2))
            {
                r = rgbColorState[stateCnt].color[0] * rgb_scnt / (SHOW_TIME / 2);
                g = rgbColorState[stateCnt].color[1] * rgb_scnt / (SHOW_TIME / 2);
                b = rgbColorState[stateCnt].color[2] * rgb_scnt / (SHOW_TIME / 2);
            }
            else
            {
                r = rgbColorState[stateCnt].color[0] * (SHOW_TIME - rgb_scnt) / (SHOW_TIME / 2);
                g = rgbColorState[stateCnt].color[1] * (SHOW_TIME - rgb_scnt) / (SHOW_TIME / 2);
                b = rgbColorState[stateCnt].color[2] * (SHOW_TIME - rgb_scnt) / (SHOW_TIME / 2);
            }
            break;
        default:
            break;
        }
        rgb_set(r, g, b);
    }
    else
    {
        while (!((1 << stateCnt) & rgb_state))
        {
            stateCnt++;
            if (stateCnt >= RGB_STATE_COUNT)
            {
                stateCnt = 0;
                break;
            }
        }
    }
}
